package test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main extends Thread {
	private final InputStream _is;
	private final OutputStream _os;
	private final OutputStream _ax;

	public Main(String name, InputStream is, OutputStream os, OutputStream ax) {
		super(name);
		setDaemon(true);
		_is = is;
		_os = os;
		_ax = ax;
	}

	public static void main(String... args) throws IOException {
		ServerSocket server = newServerSocket();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
		System.out.println("started");
		for (;;) {
			Socket socket = server.accept();
			Socket client = newClientSocket();
			Date date = newDate();
			String dt = format.format(date);
			System.out.println("connected " + dt);
			new Main(dt + ":request",
					socket.getInputStream(),
					client.getOutputStream(),
					new FileOutputStream(dt + ".rq")).start();
			new Main(dt + ":response",
					client.getInputStream(),
					socket.getOutputStream(),
					new FileOutputStream(dt + ".rs")).start();
		}
	}

	static ServerSocket newServerSocket() throws IOException {
		InetAddress addr = InetAddress.getByName(System.getProperty("server.addr", "0.0.0.0"));
		int port = Integer.getInteger("server.port", 7777);
		return new ServerSocket(port, 50, addr);
	}

	static Socket newClientSocket() throws IOException {
		InetAddress addr = InetAddress.getByName(System.getProperty("client.addr", "127.0.0.1"));
		int port = Integer.getInteger("client.port", 80);
		return new Socket(addr, port);
	}

	static long _prev = System.currentTimeMillis();
	static Date newDate() {
		long curr;
		do {
			curr = System.currentTimeMillis();
		} while (curr == _prev);
		_prev = curr;
		return new Date(curr);
	}

	public void run() {
		byte[] buffer = new byte[4096];
		int r;
		try {
			try {
				try {
					try {
						while ((r = _is.read(buffer)) != -1) {
							_os.write(buffer, 0, r);
							_os.flush();
							_ax.write(buffer, 0, r);
							_ax.flush();
						}
					} finally {
						_is.close();
					}
				} finally {
					_os.close();
				}
			} finally {
				_ax.close();
			}
		} catch (IOException exc) {
			System.out.println("exception " + getName() + "\t" + exc);
		}
		System.out.println("finished " + getName());
	}
}
